<template>
  <div class="app-container">
    <div class="label" :loading="createCombinationLabelLoading">
      <el-row type="flex">
        <el-col :span="4">
          <div class="grid-content title">顾客组合标签</div>
        </el-col>
      </el-row>
      <el-row type="flex" style="margin-top: 20px;">
        <el-col :span="24">
          <el-form ref="label" :model="label" :rules="labelRules" inline>
            <el-form-item label="组合标签名称" prop="name">
              <el-input v-model="label.name" placeholder="请输入组合标签名称" style="width: 250px" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row type="flex" style="margin-top:20px;">
        <el-col :span="4" style="color: #606266; font-size: 14px;font-weight: 700">标签设定区域</el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <div class="label-setting">
            <el-row type="flex" justify="space-between" class="label-header">
              <el-col :span="5" style="color: #5677fc; cursor: pointer">
                <div @click="handleAddLabel">+ 新增基础标签</div>
              </el-col>
              <el-col :span="5" style="color: #606266">标签阙值设定区域</el-col>
            </el-row>
            <!-- 已选标签设定区域 -->
            <el-row>
              <el-col :span="22">
                <div class="table-label">
                  <el-row>
                    <el-col :span="8" style="text-align: center;color: #606266">已选择基础标签</el-col>
                    <el-col :span="8" style="text-align: center;color: #333">标签类型</el-col>
                    <el-col :span="8" style="text-align: center;color: #333">标签阙值</el-col>
                  </el-row>
                  <div class="label-list">
                    <el-row v-for="(basicLabel, index) of labelList" :key="basicLabel.labelName" style="display:flex;align-items:center">
                      <el-col :span="8">
                        <div class="label-item">
                          <div :class="['select-icon', basicLabel.chooseActive ? 'active' : '']" @click="handleSelectLabel(index)">
                            <span :class="['icon-inner', basicLabel.chooseActive ? 'active' : '']" />
                          </div>
                          <div class="label-name">{{ basicLabel.labelName }}</div>
                          <div :class="['delete', basicLabel.chooseActive ? '' : 'active']" @click="handleDeleteLabel(basicLabel, index)">
                            <svg-icon icon-class="delete" />
                          </div>
                        </div>
                      </el-col>
                      <el-col :span="8">
                        <div v-if="basicLabel.valueType === '00'" class="label-item center">
                          {{ '数值型' }}
                        </div>
                        <div v-else-if="basicLabel.valueType === '01'" class="label-item center">
                          {{ '单选型' }}
                        </div>
                        <div v-else-if="basicLabel.valueType === '02'" class="label-item center">
                          {{ '多选型' }}
                        </div>
                        <div v-else class="label-item center">
                          {{ '标签型' }}
                        </div>
                      </el-col>
                      <el-col :span="8">
                        <div class="label-item">
                          <!-- 根据标签类型设置不同的选择条件 -->
                          <div v-if="basicLabel.valueType === '00'" class="select-area">
                            <el-select v-model="basicLabel.activeOption" placeholder="请选择" style="width: 100px;height: 30px">
                              <el-option
                                v-for="item in basicLabel.basisLabelValueList"
                                :key="item.id"
                                :label="item.labelValue"
                                :value="item.id"
                              />
                            </el-select>
                            <el-input v-model="basicLabel.value" type="number" placeholder="请输入阙值" style="width: 120px;height:30px" />
                          </div>
                          <div class="select-area">
                            <el-select
                              v-if="basicLabel.valueType === '01'"
                              v-model="basicLabel.activeOption"
                              placeholder="请选择"
                              style="width: 250px"
                            >
                              <el-option
                                v-for="item in basicLabel.basisLabelValueList"
                                :key="item.id"
                                :label="item.labelValue"
                                :value="item.id"
                              />
                            </el-select>
                            <el-select
                              v-if="basicLabel.valueType === '02'"
                              v-model="basicLabel.activeOption"
                              multiple
                              placeholder="请选择"
                              style="width: 250px"
                            >
                              <el-option
                                v-for="item in basicLabel.basisLabelValueList"
                                :key="item.id"
                                :label="item.labelValue"
                                :value="item.id"
                              />
                            </el-select>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </el-col>
            </el-row>
            <!-- 所选标签预计人数 -->
            <el-row v-if="false">
              <el-col :span="24">
                <div class="calculate-count">
                  组合标签预计人数: <span class="count">{{ calculateCount }}</span>人
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="confirm-cancel">
            <el-button type="primary" @click="handleConfirmLabelCombine">确认</el-button>
            <el-button type="info" plain @click="handleCancelLabelCombine">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      :visible.sync="addLabelVisible"
      title="基础标签类型"
      width="60%"
      :before-close="handleAddLabelClose"
    >
      <span class="sub-title">可通过类型筛选标签</span>
      <el-row>
        <el-col :span="24">
          <div class="basic-label">
            <el-row>基础标签类型</el-row>
            <el-row>
              <el-col :span="24">
                <div class="label-search">
                  <el-select
                    v-model="type"
                    placeholder="请选择"
                    style="width: 150px;height: 30px"
                    @change="handleLabelTypeChange"
                  >
                    <el-option
                      v-for="item in labelTypeList"
                      :key="item.type"
                      :label="item.typeName"
                      :value="item.type"
                    />
                  </el-select>
                  <el-input
                    v-model="labelName"
                    placeholder="请输入标签名"
                    style="width: 160px;height:30px"
                    @input="handleChangeLabelName"
                  />
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div :loading="queryLabelLoading" class="choose-label">
                  <div v-for="(chooseLabel, index) of chooseLabelList" :key="chooseLabel.labelName" class="choose-label-item">
                    <div :class="['select-icon', chooseLabel.chooseActive ? 'active' : '']" @click="handleChooseLabel(chooseLabel, index)">
                      <span :class="['icon-inner', chooseLabel.chooseActive ? 'active' : '']" />
                    </div>
                    <div class="label-name">{{ chooseLabel.labelName }}</div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-pagination
                  layout="prev, pager, next"
                  :page-size="pageSize"
                  :total="totalSize"
                  @current-change="handleChangePage"
                />
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="label-operation">
            <el-button type="primary" @click="handleConfirmChooseLabel">确认</el-button>
            <el-button type="info" plain @click="handleAddLabelClose">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getLabelTypeList, getBasisLabelList, getUpdateCombinationLabel, getCreateCombinationLabel, getCombinationLabelDetail } from '@/api/coupon/label'
export default {
  name: 'Label',
  data() {
    return {
      label: {
        name: ''
      },
      addLabelVisible: false,
      labelRules: {
        name: [
          { required: true, message: '请输入组合标签名称', trigger: 'blur' }
        ]
      },
      labelType: '',
      labelTypeList: [],
      searchLabelName: '',
      totalLabelCount: 500,
      // 待选择标签
      chooseLabelList: [],
      /**
       * 已选标签，但未确认
       */
      choosingLabelList: [],
      // 已选标签
      labelList: [],
      calculateCount: '1999',
      /**
       * 查询基础标签参数
       */
      queryLabelLoading: false,
      pageNum: 1,
      pageSize: 15,
      type: '', // 基础标签类型
      labelName: '',
      /**
       * 查询基础标签返回数据
       */
      totalSize: 0,
      createCombinationLabelLoading: false,
      /**
       * 标识此次动作是更新还是新增礼券
       * 00 默认新增
       * 01 从礼券发放设定跳转过来
       * 02 编辑原有礼券信息
       */
      editType: '00',
      // 更新原有组合标签需要状态
      id: '',
      labelId: ''
    }
  },
  /**
   * 钩子函数
   */
  async created() {
    await this.getLabelTypeList()
    /**
     * 根据路由参数判断是从哪个入口过来的
     */
    this.getRouteParam()
    if (this.editType === '02') {
      this.getLabelDetail()
    }
    this.getBasisLabel()
  },
  methods: {
    /**
     * 获取标签详情
     */
    async getLabelDetail() {
      const { labelId } = this
      const labelDetail = await getCombinationLabelDetail(labelId)
      const { combinationLabelValueList, labelIdValueListHashMap } = labelDetail.combinationLabel
      for (let i = 0; i < combinationLabelValueList.length; i++) {
        const labelValue = combinationLabelValueList[i]
        const labelInfo = {}
        this.$set(labelInfo, 'chooseActive', true)
        this.$set(labelInfo, 'valueType', labelValue.sysLabelValueType)
        this.$set(labelInfo, 'labelName', labelValue.sysLabelName)
        this.$set(labelInfo, 'label', labelValue.sysLabelLabel)
        this.$set(labelInfo, 'basisLabelValueList', labelIdValueListHashMap[labelValue.sysLabelId])
        // 后端返回的是 String 类型
        if (labelValue.sysLabelValueType === '02') {
          const systemValue = labelValue.sysLableValueId.split(',')
          const actionOption = systemValue.map(ele => Number(ele))
          this.$set(labelInfo, 'activeOption', actionOption)
        } else {
          this.$set(labelInfo, 'activeOption', Number(labelValue.sysLableValueId))
        }
        if (labelValue.conditionalValue) {
          this.$set(labelInfo, 'value', Number(labelValue.conditionalValue))
        }
        this.labelList.push(labelInfo)
      }
      this.choosingLabelList = this.labelList
      this.getBasisLabel()
    },
    /**
     * 页面初始化
     * 获取路由传递过来的参数
     */
    getRouteParam() {
      const { params } = this.$route
      const { editType } = params
      if (editType) {
        this.editType = editType
        if (editType === '02' && JSON.stringify(params) !== '{}') {
          this.label.name = params.name
          this.labelName = params.labelName
          this.id = params.id
          this.labelId = params.labelId
        }
      }
    },
    /**
     * 选择/取消选择标签
     * 操作已经选择的标签
     */
    handleSelectLabel(index) {
      const labelList = this.labelList
      labelList[index].chooseActive = !labelList[index].chooseActive
      this.labelList = labelList
    },
    /**
     * 删除选择标签
     */
    handleDeleteLabel(label, index) {
      const labelList = this.labelList
      /**
       * 点击删除
       * 删除已选择列表中的数据
       * 删除暂存区标签中的数据
       */
      const list = labelList.filter((ele, i) => {
        return i !== index
      })
      const choosingList = this.choosingLabelList.filter((ele) => {
        return ele.labelName !== label.labelName
      })
      this.labelList = [...list]
      this.choosingLabelList = [...choosingList]
    },
    handleAddLabelClose() {
      this.addLabelVisible = false
    },
    handleAddLabel() {
      this.addLabelVisible = true
    },
    handleConfirmLabelSetting() {

    },
    /**
     * 选择标签之后
     * 操作基础标签
     * 更新暂存区标签
     */
    handleChooseLabel(label, index) {
      const labelList = this.chooseLabelList
      labelList[index].chooseActive = !labelList[index].chooseActive
      this.chooseLabelList = labelList
      /**
       * 记录已经选择的标签
       * 以便于分页之后依然记录当前选择状态
       */
      let labelIndex = -1
      for (let i = 0; i < this.choosingLabelList.length; i++) {
        if (this.choosingLabelList[i].labelName === label.labelName) {
          labelIndex = i
        }
      }
      if (label.chooseActive) {
        if (labelIndex === -1) {
          this.choosingLabelList = [...this.choosingLabelList, label]
        }
      } else {
        const choosingLabelList = this.choosingLabelList.filter((ele) => {
          return ele.labelName !== label.labelName
        })
        this.choosingLabelList = [...choosingLabelList]
      }
    },
    /**
     * 确认标签选择
     */
    handleConfirmChooseLabel() {
      const chooseLabelList = this.choosingLabelList
      for (let i = 0; i < chooseLabelList.length; i++) {
        let index = -1
        for (let j = 0; j < this.labelList.length; j++) {
          if (chooseLabelList[i].labelName === this.labelList[j].labelName) {
            index = i
          }
        }
        if (index === -1) {
          this.labelList = [...this.labelList, chooseLabelList[i]]
        }
        index = -1
      }
      /**
       * 设置选择条件默认选择值
       */
      this.setLabelSelect()
      this.handleAddLabelClose()
    },
    /**
     * 设置标签阙值的默认选择条件
     */
    setLabelSelect() {
      for (let i = 0; i < this.labelList.length; i++) {
        const labelList = this.labelList[i].basisLabelValueList
        const activeOption = labelList === null ? '' : labelList[0].id
        this.$set(this.labelList[i], 'activeOption', activeOption)
        /**
         * 设置单选、多选
         */
        if (this.labelList[i].valueType === '02') {
          this.$set(this.labelList[i], 'activeOption', [])
        } else {
          this.$set(this.labelList[i], 'activeOption', activeOption)
        }
        if (this.labelList[i].valueType === '00') {
          this.$set(this.labelList[i], 'value', 0)
        }
      }
    },
    /**
     * 选择标签逻辑
     * 点击新增基础标签 => 弹出基础标签列表 => 选择基础标签
     * 点击确认 => 追加到已选择的标签列表中
     * 点击取消 => 什么事也不做
     * 点击标签选择 => 弹出基础标签列表，需要做一个过滤，已经选择的不展示在列表展示中
     * 以此循环
     */
    /**
     * 获取标签类型
     */
    async getLabelTypeList() {
      const res = await getLabelTypeList()
      this.labelTypeList = res
    },
    /**
     * 获取基础标签
     */
    async getBasisLabel() {
      const { pageNum, pageSize, type, labelName } = this
      const requestData = {
        pageNum,
        pageSize,
        queryParamMap: {}
      }
      if (type) {
        requestData.queryParamMap.type = type
      }
      if (labelName) {
        requestData.queryParamMap.labelName = labelName
      }
      this.queryLabelLoading = true
      const res = await getBasisLabelList(requestData)
      console.log('res is', res)
      this.queryLabelLoading = false
      this.totalSize = res.totalSize
      const list = res.content
      for (let i = 0; i < list.length; i++) {
        this.$set(list[i], 'chooseActive', false)
      }
      this.chooseLabelList = list
      this.setChooseStateOfChooseLabel()
    },
    // 选择标签类型改变
    handleLabelTypeChange() {
      this.pageNum = 1
      this.getBasisLabel()
    },
    // 模糊搜索词
    handleChangeLabelName() {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.handleLabelTypeChange()
      }, 200)
    },
    /**
     * 分页查询
     */
    async handleChangePage(num) {
      this.pageNum = num
      this.getBasisLabel()
    },
    /**
     * 设置当前展示标签的选中状态
     */
    setChooseStateOfChooseLabel() {
      const { choosingLabelList, chooseLabelList } = this
      if (choosingLabelList.length === 0 || chooseLabelList.length === 0) {
        return
      }
      for (let i = 0; i < choosingLabelList.length; i++) {
        let index = -1
        let labelIndex = 0
        for (let j = 0; j < chooseLabelList.length; j++) {
          if (choosingLabelList[i].labelName === chooseLabelList[j].labelName) {
            index = i
            labelIndex = j
          }
        }
        if (index === -1) {
          chooseLabelList[labelIndex].chooseActive = false
        } else {
          chooseLabelList[labelIndex].chooseActive = true
        }
        index = -1
      }
      this.chooseLabelList = chooseLabelList
    },
    /**
     * 提交组合标签相关信息
     */
    async handleConfirmLabelCombine() {
      /**
       * 确认组合标签
       * 先处理数据
       */
      if (!this.label.name) {
        this.$message('请输入组合标签名称')
        return
      }
      if (this.labelList.length === 0) {
        this.$message('请选择基础标签')
        return
      }
      let chooseLength = 0
      for (let i = 0; i < this.labelList.length; i++) {
        if (this.labelList[i].chooseActive) {
          chooseLength++
        }
      }
      if (chooseLength === 0) {
        this.$message('请确认基础标签选择')
        return
      }

      const requestData = {
        name: this.label.name
      }
      const combinationLabelValueList = []
      console.log('this.labelList is', this.labelList)
      for (let i = 0; i < this.labelList.length; i++) {
        if (this.labelList[i].valueType === '02') {
          const labelValue = {}
          labelValue.sysLabelId = this.labelList[i].id
          labelValue.sysLabelValueType = this.labelList[i].valueType
          labelValue.sysLabelLabel = this.labelList[i].label
          labelValue.sysLabelName = this.labelList[i].labelName
          // 多选选中 value id
          labelValue.sysLableValueId = this.labelList[i].activeOption.join(',')
          const basisLabelValueList = this.labelList[i].basisLabelValueList
          const sysLabelValue = []
          basisLabelValueList.forEach((ele) => {
            if (this.labelList[i].activeOption.indexOf(ele.id) > -1) {
              sysLabelValue.push(`'${ele.labelValue}'`)
            }
          })
          labelValue.sysLableValue = sysLabelValue.join(',')
          combinationLabelValueList.push(labelValue)
        } else if (this.labelList[i].valueType === '00' || this.labelList[i].valueType === '01') {
          const labelValue = {}
          let activeBasisLabelValue
          const basisLabelValueList = this.labelList[i].basisLabelValueList
          for (let j = 0; j < basisLabelValueList.length; j++) {
            if (this.labelList[i].activeOption === basisLabelValueList[j].id) {
              activeBasisLabelValue = basisLabelValueList[j]
            }
          }
          labelValue.sysLabelId = activeBasisLabelValue.labelId
          labelValue.sysLabelValueType = this.labelList[i].valueType
          labelValue.sysLabelLabel = this.labelList[i].label
          labelValue.sysLabelName = this.labelList[i].labelName
          labelValue.sysLableValueId = activeBasisLabelValue.id
          labelValue.sysLableValue = activeBasisLabelValue.labelValue
          if (this.labelList[i].valueType === '00') {
            labelValue.conditionalValue = this.labelList[i].value
          }
          combinationLabelValueList.push(labelValue)
        } else if (this.labelList[i].valueType === '03') {
          /* 有赞标签，没有选项，标签带信息 */
          const labelValue = {}
          const basisLabelValueList = this.labelList[i].basisLabelValueList
          labelValue.sysLabelValueType = this.labelList[i].valueType
          labelValue.sysLabelLabel = this.labelList[i].label
          labelValue.sysLabelName = this.labelList[i].labelName
          labelValue.sysLableValueId = basisLabelValueList[0].id
          labelValue.sysLabelId = basisLabelValueList[0].labelId
          labelValue.sysLableValue = basisLabelValueList[0].labelValue
          combinationLabelValueList.push(labelValue)
        }
      }
      console.log(combinationLabelValueList)
      requestData.combinationLabelValueList = combinationLabelValueList
      this.createCombinationLabelLoading = true
      setTimeout(() => {
        this.createCombinationLabelLoading = false
      }, 5000)
      if (this.editType === '00') {
        await getCreateCombinationLabel(requestData)
      } else {
        /* 更新的时候需要传递 labelId */
        requestData.id = this.id
        requestData.labelId = this.labelId
        await getUpdateCombinationLabel(requestData)
      }
      this.createCombinationLabelLoading = false

      if (this.editType === '02') {
        this.$message({
          message: '修改成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '组合标签创建成功',
          type: 'success'
        })
      }
      this.setCombinationLabelInit()
      this.$router.go(-1)
      // if (this.editType === '01' || this.editType === '02') {
      //   // 如果是从其他页面跳转过来的编辑的，则跳转回上一层
      //   this.$router.go(-1)
      // }
    },
    /**
     * 取消创建组合标签
     */
    handleCancelLabelCombine() {
      try {
        this.$router.go(-1)
      } catch (err) {
        this.$router.push('/dashboard')
      }
    },
    // 初始化创建组合标签数据
    setCombinationLabelInit() {
      this.chooseLabelList = []
      this.choosingLabelList = []
      this.label.name = ''
      this.type = ''
      this.labelName = ''
      this.labelList = []
      this.pageNum = 1
      this.getBasisLabel()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .label{
    width: 100%;
    min-height: 90px;
    border-radius: 6px;
    background: #ffffff;
    padding-top: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
    padding-right: 20px;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
    .title{
      font-size: 16px;
      color: #606266;
    }
    /* 标签设置区域 */
    .label-setting{
      margin-top: 10px;
      padding: 10px 20px;
      width: 100%;
      background: #fafafa;
      font-size: 14px;
      border: 1px dashed #dcdcdc;
      border-radius: 2px;
      .label-header{
        padding: 4px 0;
      }
      .table-label{
        margin-top: 10px;
        padding: 10px;
        width: 100%;
        background: #ffffff;
        font-size: 14px;
        border: 1px dashed #e1e1e1;
        border-radius: 2px;
        .label-list{
          margin-top: 10px;
          color: #606266;
          .label-item{
            display: flex;
            align-items: center;
            padding: 4px 0px;
            width: 80%;
            margin-left: 10%;
            &.center{
              justify-content: center;
            }
            .select-icon{
              margin-left: 8px;
              display: flex;
              justify-content: center;
              align-items: center;
              width: 18px;
              height: 18px;
              border-radius: 50%;
              border: 1px solid #606266;
              cursor: pointer;
              transition: all .2s ease-in-out;
              &.active{
                border-color: #5677fc;
              }
              .icon-inner{
                width: 10px;
                height: 10px;
                border-radius: 50%;
                background: transparent;
                transition: all .2s ease-in-out;
                &.active{
                  background: #5677fc;
                }
              }
            }
            .label-name{
              margin-left: 10px;
              color: #333;
            }
            .delete{
              margin-left: 10px;
              visibility: hidden;
              cursor: pointer;
              transition: all .2s ease-in-out;
              &.active{
                visibility: visible;
              }
            }
          }
        }
      }
      .calculate-count{
        margin-top: 50px;
        margin-bottom: 10px;
        .count{
          font-size: 22px;
          font-weight: 600;
        }
      }
    }
    /* 确认/取消 */
    .confirm-cancel{
      margin-top: 25px;
      margin-bottom: 8px;
    }
  }
  /* dialog 样式 */
  .sub-title{
    position: absolute;
    top: 24px;
    left: 135px;
  }
  .basic-label{
    padding: 15px;
    width: 100%;
    background: #fafafa;
    font-size: 14px;
    border: 1px dashed #e1e1e1;
    border-radius: 2px;
    .label-search{
      margin-top: 15px;
    }
    .choose-label{
      width: 100%;
      margin-top: 15px;
      margin-bottom: 6px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      .choose-label-item{
        box-sizing: border-box;
        width: 33.33%;
        display: flex;
        align-items: center;
        padding: 6px;
        .select-icon{
          display: flex;
          justify-content: center;
          align-items: center;
          width: 18px;
          height: 18px;
          border-radius: 50%;
          border: 1px solid #606266;
          cursor: pointer;
          transition: all .2s ease-in-out;
          &.active{
            border-color: #5677fc;
          }
          .icon-inner{
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: transparent;
            transition: all .2s ease-in-out;
            &.active{
              background: #5677fc;
            }
          }
        }
        .label-name{
          margin-left: 10px;
          color: #333;
        }
      }
    }
  }
  .label-operation{
    margin-top: 15px;
  }
</style>
